package com.lscdu.gulimall.ruoyi_springboot.service.impl;

import com.lscdu.gulimall.ruoyi_springboot.bean.system.SysConfig;
import com.lscdu.gulimall.ruoyi_springboot.common.core.redis.RedisCache;
import com.lscdu.gulimall.ruoyi_springboot.mapper.SysConfigMapper;
import com.lscdu.gulimall.ruoyi_springboot.service.ISysConfigService;
import com.lscdu.gulimall.ruoyi_springboot.utis.constant.CacheConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author 啊昌
 * @date 2024/9/2 14:49
 * ISysConfigServiceimp
 */

@Service
public class ISysConfigServiceimpl implements ISysConfigService {

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private SysConfigMapper sysConfigMapper;

	//验证码开关
	@Override
	public boolean selectCaptchaEnabled() {
		//1 从redis 缓存中获取 验证码开关
		String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
		if(captchaEnabled ==null){
			return true;
		}
		return Boolean.valueOf(captchaEnabled);
	}


	/**
	 * 根据键名查询参数配置信息
	 *
	 * @param configKey 参数key
	 * @return 参数键值
	 */
	@Override
	public String selectConfigByKey(String configKey) {
		//  从redis缓存中获取验证码的开关
		String cacheObject = (String)redisCache.getCacheObject(getCacheKey(configKey));
		//redis 有数据直接返回
		if(!StringUtils.isEmpty(cacheObject)){
			return cacheObject;
		}
		//没有数据 从mysq查询数据 存储在redis
		SysConfig sysConfig = new SysConfig();
		sysConfig.setConfigKey(configKey);
		//从mysql 查询到数据返回
		SysConfig retConfig = sysConfigMapper.selectConfig(sysConfig);
		if(retConfig != null){
			redisCache.setCacheObject(getCacheKey(configKey),retConfig.getConfigValue());
			return retConfig.getConfigValue();
		}
		return "";
	}

	/**
	 * 设置cache key
	 *
	 * @param configKey 参数键
	 * @return 缓存键key
	 */
	private String getCacheKey(String configKey) {
		//redis 缓存的key sys_config:achang.sys.account.captchaEnabled
		return CacheConstants.SYS_CONFIG_KEY + configKey;
	}
}
